<template>

  <Col :lg="24" :md="16">
    <Card class="warp-card" dis-hover>
      <!--Row 顶部操作区 start-->
      <Row justify="space-between" type="flex">
        <Col>
          <Input
            placeholder="请输入工号搜索"
            style="width: 200px;"
            v-model="searchForm.workNo"
          />
          <Input
            placeholder="请输入姓名搜索"
            style="width: 200px;margin-left:20px;"
            v-model="searchForm.name"
          />
          <Input
            placeholder="请输入机构搜索"
            style="width: 200px;margin-left:20px;"
            v-model="searchForm.orgName"
          />
          <Button
            @click="searchData" icon="md-search"
            style="margin-left: 20px;"
            type="primary"
            v-privilege="'search-user'"
          >查询
          </Button>
          <Button
            @click="clearSearch"
            style="margin-left: 20px;"
            icon="md-refresh"
            type="default"
            v-privilege="'search-user'"
          >重置
          </Button>
        </Col>
        <Col>
          <Button
            @click="showAddUserModal"
            icon="md-add"
            type="primary"
            v-privilege="'add-user'"
          >新建
          </Button>
        </Col>
      </Row>
      <!--Row 顶部操作区 end-->
      <!--Row 表格区 start-->
      <Row style="padding-top:10px; ">
        <Table
          :columns="columns"
          :data="userTable"
          :loading="isShowTablesLoading"
          @on-selection-change="singleSelect"
          border
        ></Table>
      </Row>
      <!--Row 表格区 end-->
      <!--Row 底部操作区 start-->
      <Row class="page" justify="end" style="position: relative;margin-top: 10px;" type="flex">
        <Page
          :current="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :total="totalPage"
          @on-change="changePage"
          show-total
          show-elevator
        ></Page>
      </Row>
      <!--Row 底部操作区 end-->
    </Card>

    <!--UserTableAdd 添加成员弹窗 start-->
    <UserTableAdd @addSuccess="getUserList"
      ref="userTableAdd"
    ></UserTableAdd>
    <UserTableDetail ref="userTableDetail"></UserTableDetail>

  </Col>


</template>
<script>
import {userApi} from '@/api/sys-user';
import UserTableAdd from '../user-table-add/user-table-add.vue';
import UserTableDetail from '../user-table-detail/user-table-detail.vue';

export default {
  name: 'UserTable',
  components: {
    UserTableAdd,
    UserTableDetail
  },
  data() {
    return {
      userRole: [],
      // 员工id
      mid: '',
      totalPage: 0,
      isShowManageRoleModal: false,
      isShowTablesLoading: false,
      // 搜索框内容
      searchForm: {
        workNo: '',
        name: '',
        orgName: '',
        searchCount: true,
        sort: false,
        pageNum: 1,
        pageSize: 20,
      },
      searchFormInt: {
        workNo: '',
        name: '',
        orgName: ''
      },
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          key: 'workNo',
          width: 120,
          title: '工号',
          align: 'left'
        },
         {
          key: 'username',
          width: 80,
          title: '用户名',
          align: 'left'
        },
        {
          key: 'actualName',
          width: 80,
          title: '姓名',
          align: 'left'
        },
        {
          key: 'orgName',
          title: '所属机构',
          width: 180,
          align: 'left'
        },
        {
          key: 'departmentName',
          title: '所属部门',
          width: 120,
          align: 'left'
        },
        {
          key: 'userTypeName',
          title: '用户类型',
          width: 80,
          align: 'left'
        },
        {
          key: 'roleName',
          width: 80,
          title: '角色名称',
          align: 'left'
        },
        {
          key: 'positionName',
          title: '职务',
          width: 80,
          align: 'left'
        },
        {
          key: 'phone',
          title: '电话号码',
          width: 100,
          align: 'left'
        },
        {
          key: 'email',
          title: '邮箱',
          width: 180,
          align: 'left'
        },
        {
          key: 'isDisabled',
          width: 80,
          title: '状态',
          align: 'left',
          render: (h, params) => {
            let disabled = params.row.isDisabled;
            return h('i-switch', {
                props: {
                  size: "large",
                  value: !disabled
                },
                on: {
                  'on-change': (value) => {
                    params.row.status = value;
                    const th = this;
                    this.updateUserStatus(th,params);
                  }
                }
              },
              [h('span', {
                slot: "open",
                domProps: {
                  innerHTML: '启用'
                }
              }),
                h('span', {
                  slot: "close",
                  domProps: {
                    innerHTML: '禁用'
                  }
                }),
              ]
            )
          }
        },
        {
          key: 'createTime',
          width: 160,
          title: '创建时间',
          align: 'left'
        },
        {
          title: '操作',
          key: 'action',
          width: 160,
          fixed: 'right',
          align: 'center',
          className: 'action-hide',
          render: (h, params) => {
            let btnGroup = [];
            let isSuper = params.row.super
            // btnGroup.push({
            //   title: '详情',
            //   action: () => {
            //     this.$refs['UserTableDetail'].showModal(params.row);
            //   }
            // });
            if (params.row.isDisabled == 0 && !isSuper) {
              btnGroup.push({
                title: '编辑',
                directives: [
                  {
                    name: 'privilege',
                    value: 'update-user'
                  }
                ],
                action: () => {
                  this.updataUser(params.row);
                }
              });
            }
            if (!isSuper) {
              btnGroup.push({
                title: '重置密码',
                directives: [
                  {
                    name: 'privilege',
                    value: 'reset-user-password'
                  }
                ],
                action: () => {
                  this.$Modal.confirm({
                    title: '重置密码',
                    content: '是否将密码重置为123456',
                    onOk: () => {
                      this.resetPassword(params.row.id);
                    }
                  });
                }
              });
            }
            if (params.row.isDisabled == 1 && !isSuper) {
              btnGroup.push({
                title: '删除',
                directives: [
                  {
                    name: 'privilege',
                    value: 'delete-user'
                  }
                ],
                action: () => {
                  this.$Modal.confirm({
                    title: '删除',
                    content: '确认删除？',
                    onOk: () => {
                      this.deleteUser(params.row.id);
                    }
                  });
                }
              });
            }
            return this.$tableAction(h, btnGroup);
          }
        }
      ],
      // 表格数据
      userTable: [],
      disableId: [],
      currentDisabled: 0,
      roleList: []
    };
  },
  computed: {},
  filters: {},
  created() {
  },
  mounted() {
    this.getUserList();
  },
  beforeCreate() {
  },
  beforeMount() {
  },
  beforeUpdate() {
  },
  updated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  activated() {
  },
  methods: {
    // 翻页
     // 页码改变
    changePage(pageNum) {
      this.searchForm.pageNum = pageNum;
      this.getUserList();
    },
    // 改变每页显示数据条数
    changePageSize(pageSize) {
      this.searchForm.pageNum = 1;
      this.searchFrom.pageSize = pageSize;
      this.getUserList();
    },
    // 搜索
    searchData() {
      this.pageNum = 1;
      this.getUserList();
    },
    // 重置
    clearSearch() {
      Object.assign(this.searchForm, this.searchFormInt);
      this.getUserList();
    },
    // 根据部门ID查询部门员工
    async getUserList() {
      try {
        this.isShowTablesLoading = true;
        let result = await userApi.getUserList(this.searchForm);
        this.totalPage = result.data.total;
        this.userTable = result.data.list;
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowTablesLoading = false;
      }
    },
    // 打开子组件的模态框
    showAddUserModal() {
      this.$refs.userTableAdd.showModal();
    },
    // 修改用户信息
    updataUser(detail) {
      this.$refs.userTableAdd.showModal(detail.id);
    },
    // 表格左侧复选框，点击保存选中栏信息
    singleSelect(row) {
      this.disableId = row;
    },
    // 批量禁用
    GroupDisable(type) {
      if (this.disableId.length == 0) {
        this.$Message.error('请最少选择一项');
        return false;
      } else {
        this.currentDisabled = type;
        let disableIds = this.disableId.map(e => e.id);
        this.updateStatusBatch(
          Object.assign({status: type, userIds: disableIds})
        );
      }
    },
    // 禁用/启用单个用户
    async updateUserStatus(h,params) {
      try {
        this.isShowTablesLoading = true;
        let userId = params.row.id;
        let status = params.row.status;
        let result = await userApi.updateStatus(userId, status?0:1);
        this.isShowTablesLoading = false;
        if (!status) {
          this.$Message.success('禁用成功');
        } else {
          this.$Message.success('启用成功');
        }
        this.getUserList();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 批量禁用多个用户
    async updateStatusBatch(param) {
      try {
        this.isShowTablesLoading = true;
        let result = await userApi.updateStatusBatch(param);
        this.isShowTablesLoading = false;
        this.$Message.success('操作成功');
        this.disableId = [];
        this.getUserList();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 重置密码
    async resetPassword(id) {
      try {
        this.isShowTablesLoading = true;
        let result = await userApi.resetPassword(id);
        this.isShowTablesLoading = false;
        this.$Message.success('操作成功');
        this.getUserList();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 删除成员
    async deleteUser(id) {
      try {
        this.isShowTablesLoading = true;
        let result = await userApi.deleteUser(id);
        this.isShowTablesLoading = false;
        this.$Message.success('操作成功');
        this.getUserList();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.ivu-tree-children {
  cursor: pointer;
}

.option-department {
  font-size: 14px;
  padding: 5px;
  cursor: pointer;
}

.searchable-table-con1 {
  min-height: 350px !important;
}

.option-department:hover {
  background-color: rgba(5, 170, 250, 0.2);
}
</style>
